var selectedStationId='';
var selectedStationNo='';
var selectedStationName='';
jQuery(document).ready(function() {
	Metronic.init();
	Layout.init();
	QuickSidebar.init();
	Demo.init();
	
	$("#serchButton").click(function() {
		tableStationInit.fnDraw();
	});
	
	$("#serchBillButton").click(function() {
		tableBillInit.fnDraw();
	});
	
	$('.date-picker').datepicker({
		language : 'cn',
		todayBtn : false,
		autoclose : true,
		forceParse : true,
		format : "yyyy-mm-dd"
	});
	
	//初始化基站列表
	var tableStationInit = $("#table_station").dataTable({
		"paging" : true, //翻页功能
		"lengthChange" : true, //改变每页显示数据数量
		"searching" : false, //过滤功能
		"ordering" : true, //排序功能
		"order" : [ [ 0, "desc" ] ],
		"processing" : false,
		"serverSide" : true, //服务器数据
		"lengthMenu" : [ 10, 15, 30, 50 ],
		"pageLength" : 10,
		"language" : {
		"processing" : "努力加载中...",
		"search" : "搜索&nbsp;:",
		"lengthMenu" : "一页显示 _MENU_ 条数据",
		"info" : "当前第 _START_ 条到第 _END_ 条记录，共 _TOTAL_ 条记录",
		"loadingRecords" : "正在努力的加载数据...",
		"infoEmpty" : "当前第 0 条到第 0 条记录，共 0 条记录",
		"emptyTable" : "没有找到您查询的数据信息"
	},
	"ajax" : {
		"url" : "station/getStationPage",
		"type" : "POST",
		"data" : function(data) {
			data.name = $("#name").val();
			data.newNumber = $("#newNumber").val();
			data.number = $("#number").val();
		}
	},
	"columns" : [{
			"data" : "id"
		},{
			"data" : "newNumber"
		},{
			"data" : "number"
		},{
			"data" : "name"
		},{
			"orderable": false,
			"data" : null,
			"defaultContent" : "<div style='width:120'><button type='button' id='btnSelectStation' onclick='selectStation($(this))' class='btn blue btn-xs'>选择基站开始添加电费 <i class='fa fa-edit'></i></button></div>"
		}]
	});
	
	//绑定保存电费按钮
	$("#btnBillSave").click(function(){
		submitBill_validation();
	});
	
	//绑定取消保存电费按钮
	$("#btnBillCancel").click(function(){
		clearBillInput();
	});
	
	var tableBillInit = $("#table_bill").dataTable({
		"paging" : true, //翻页功能
		"lengthChange" : true, //改变每页显示数据数量
		"searching" : false, //过滤功能
		"ordering" : true, //排序功能
		"order" : [ [ 0, "desc" ] ],
		"processing" : false,
		"serverSide" : true, //服务器数据
		"lengthMenu" : [ 10, 15, 30, 50 ],
		"pageLength" : 10,
		"language" : {
		"processing" : "努力加载中...",
		"search" : "搜索&nbsp;:",
		"lengthMenu" : "一页显示 _MENU_ 条数据",
		"info" : "当前第 _START_ 条到第 _END_ 条记录，共 _TOTAL_ 条记录",
		"loadingRecords" : "正在努力的加载数据...",
		"infoEmpty" : "当前第 0 条到第 0 条记录，共 0 条记录",
		"emptyTable" : "没有找到您查询的数据信息"
	},
	"ajax" : {
		"url" : "bill/getBillPage",
		"type" : "POST",
		"data" : function(data) {
			data.stationName = $("#stationName").val();
			data.stationNo = $("#stationNo").val();
			data.billTime = $("#billTime").val();
		}
	},
	"columns" : [{
			"data" : "id"
		},{
			"data" : "cost"
		},{
			"data" : "stationNo"
		},{
			"data" : "stationName"
		},{
			"width": "120px",
			"data" : "lastTime",
			render: function ( data, type, row ) {
				if(data!=null){
					return new Date(data).toLocaleString().replace("/","年").replace("/","月").replace(" ","日 ").split(" ")[0];
		        }else{
		        	return '';
		        }
		    }
		},{
			"width": "120px",
			"data" : "currentTime",
			render: function ( data, type, row ) {
				if(data!=null){
					return new Date(data).toLocaleString().replace("/","年").replace("/","月").replace(" ","日 ").split(" ")[0];
		        }else{
		        	return '';
		        }
		    }
		},{
			"data" : "billTime"
		},{
			"data" : "jfPerson"
		},{
			"data" : "yfPerson"
		},{
			"orderable": false,
			"data" : null,
			"defaultContent" : "<div style='width:120'><button type='button' onclick='lookBillInit($(this))' class='btn blue btn-xs'>查看 <i class='fa fa-edit'></i></button><button type='button' onclick='deleteBillInit($(this))' class='btn red btn-xs'>删除 <i class='fa fa-times'></i></button></div>"
		}]
	});
});


//绑定选择基站按钮
function selectStation(obj){
	 var tableRow = obj.parents('tr')[0];
     var idTh = $(tableRow).children().get(0);
     var id = $(idTh).text();
     var noTh = $(tableRow).children().get(2)
     var no = $(noTh).text();
     var nameTh = $(tableRow).children().get(3)
     var name = $(nameTh).text();
     //修改下一个表格的表头
     var editBillTitle = $("#editBillTitle").text();
     $("#editBillTitle").html("<i class='fa fa-gift'></i>"+"新增"+name+"基站电费信息");
     selectedStationId = id;
     selectedStationNo = no;
     selectedStationName = name;
     //修改焦点
     $("#bill_billTime_edit").focus();
}

//清空基站新增表单信息
function clearInput() {
	$("#stationInfoTable input[type='text']").each(function(e) {
		$(this).val("");
	});
}

//新增基站按钮初始化
function addStationInit() {
	clearInput();
	$("#edit_station_btn").hide();
    $("#submit_station_btn").show();
    
    $("#stationInfoTable input[type='text']").each(function(e){
    	$(this).removeAttr("readonly");
    	$(this).removeAttr("style");
    	$(this).css("background-color","");
	 });
    $("#station_jfDateStr_edit").attr("readonly","readonly");
    $("#station_jfDateStr_edit").css("background-color","white");
    $("#station_jfDateStr_edit").removeAttr("disabled");
	$("#managerStation_div").modal("show");
	$("#managerStation_title").text("新增基站");
	$("#managerStation_color").attr("class","portlet box green");
	$("#station_isTuoShou_edit").removeAttr("readonly");
	$("#station_payType_edit").removeAttr("readonly");
	$("#station_isProtocol_edit").removeAttr("readonly");
	$("#station_isBeiWang_edit").removeAttr("readonly");	
	$("#station_cityArea_edit").removeAttr("readonly");
};


//查看电费按钮初始化
function lookBillInit(item) {
	clearInput();
	$("#edit_bill_btn").show();
    $("#submit_bill_btn").hide();
    $("#billInfoTableShow input[type='text']").each(function(e){
    	$(this).attr("readonly","readonly");
    	$(this).attr("style","border:0px");
    	$(this).css("background-color",$(this).parents('td').css('background-color'));
	 });
    $("#bill_lastTimeStr_show").attr("disabled", "disabled");
    $("#bill_currentTimeStr_show").attr("disabled", "disabled");
	$("#managerBill_title").text("查看电费条目详情");
	$("#managerBill_color").attr("class","portlet box blue");
    var tableRow = item.parents('tr')[0];
    var idTh = $(tableRow).children().get(0);
    $.post("bill/getBillById", 
		{ 
			id: $(idTh).text()
		}, 
		function(json){
			for(var index in json.data){
				var val = json.data[index];
				if(typeof($("#bill_"+index+"_show")) != "undefined"){
					$("#bill_"+index+"_show").val(json.data[index]);
					<!-- 下拉框处理 -->
					if(index=='ammeterBeiLv'){
						$("#bill_"+index+"_show").val(json.data[index]);						
					}
				}
			}
			
			$("#managerBill_div").modal("show");
		},"json"
	);
};

//修改按钮初始化
function editBillInit() {
	$("#edit_bill_btn").hide();
    $("#submit_bill_btn").show();
    $("#billInfoTableShow input[type='text']").each(function(e){
    	$(this).removeAttr("readonly");
    	$(this).removeAttr("style");
    	$(this).css("background-color","");
	 });
    $("#bill_lastTimeStr_show").attr("readonly","readonly");
    $("#bill_lastTimeStr_show").css("background-color","white");
    $("#bill_lastTimeStr_show").removeAttr("disabled");
    $("#bill_currentTimeStr_show").attr("readonly","readonly");
    $("#bill_currentTimeStr_show").css("background-color","white");
    $("#bill_currentTimeStr_show").removeAttr("disabled");
	$("#managerBill_title").text("修改电费条目资料");
	$("#managerBill_color").attr("class","portlet box yellow");
};


//初始化电费列表
var tableBillInit = $("#table_bill").dataTable({
	"paging" : true, //翻页功能
	"lengthChange" : true, //改变每页显示数据数量
	"searching" : false, //过滤功能
	"ordering" : true, //排序功能
	"order" : [ [ 0, "desc" ] ],
	"processing" : false,
	"serverSide" : true, //服务器数据
	"lengthMenu" : [ 10, 15, 30, 50 ],
	"pageLength" : 10,
	"language" : {
	"processing" : "努力加载中...",
	"search" : "搜索&nbsp;:",
	"lengthMenu" : "一页显示 _MENU_ 条数据",
	"info" : "当前第 _START_ 条到第 _END_ 条记录，共 _TOTAL_ 条记录",
	"loadingRecords" : "正在努力的加载数据...",
	"infoEmpty" : "当前第 0 条到第 0 条记录，共 0 条记录",
	"emptyTable" : "没有找到您查询的数据信息"
},
"ajax" : {
	"url" : "bill/getBillPage",
	"type" : "POST",
	"data" : function(data) {
		data.stationName = $("#stationName").val();
		data.stationNo = $("#stationNo").val();
		data.billTime = $("#billTime").val();
	}
},
"columns" : [{
		"data" : "id"
	},{
		"data" : "cost"
	},{
		"data" : "stationNo"
	},{
		"data" : "stationName"
	},{
		"width": "120px",
		"data" : "lastTime",
		render: function ( data, type, row ) {
			if(data!=null){
				return new Date(data).toLocaleString().replace("/","年").replace("/","月").replace(" ","日 ").split(" ")[0];
	        }else{
	        	return '';
	        }
	    }
	},{
		"width": "120px",
		"data" : "currentTime",
		render: function ( data, type, row ) {
			if(data!=null){
				return new Date(data).toLocaleString().replace("/","年").replace("/","月").replace(" ","日 ").split(" ")[0];
	        }else{
	        	return '';
	        }
	    }
	},{
		"data" : "billTime"
	},{
		"data" : "jfPerson"
	},{
		"data" : "yfPerson"
	},{
		"orderable": false,
		"data" : null,
		"defaultContent" : "<div style='width:120'><button type='button' onclick='lookBillInit($(this))' class='btn blue btn-xs'>查看 <i class='fa fa-edit'></i></button><button type='button' onclick='deleteBillInit($(this))' class='btn red btn-xs'>删除 <i class='fa fa-times'></i></button></div>"
	}]
});


//处理新增电费提交
function submitBill_validation(){
	var id = $("#bill_id_show").val();
	if(id==undefined||id==''){
		var obj = new Object();
		$("#billInfoTable input[type='text']").each(function(e){
			var inputId = $(this).attr("id");
		    var idArray = inputId.split('_');
		    if($(this).val()!=''){		    	
			    obj[idArray[1]] = $(this).val();
		    }else{
		    	obj[idArray[1]] = $(this).val();
		    }
		 });
		if(selectedStationId==''||selectedStationNo==''){
			alert("请先选择基站");
			return;
		}
		obj["stationId"] = selectedStationId;
		obj["stationNo"]=selectedStationNo;
		obj["stationName"]=selectedStationName;
		
		$("#billInfoTable select").each(function(e){
		    var inputId = $(this).attr("id");
		    var idArray = inputId.split('_');
		    if($(this).val()!=''){
			    obj[idArray[1]] = $(this).val();
		    }
		});
		
		$("#billInfoTable textarea").each(function(e){
		    var inputId = $(this).attr("id");
		    var idArray = inputId.split('_');
		    if($(this).val()!=''){
			    obj[idArray[1]] = $(this).val();
		    }
		});
		save_bill(obj);
		clearBillInput();
	}else{
		var obj2 = new Object();
		$("#billInfoTableShow input[type='text']").each(function(e){
			var stationId = $(this).attr("id");
		    var idArray = stationId.split('_');
		    obj2[idArray[1]] = $(this).val();
		 });
		var id = $("#bill_id_edit").val();
		
		$("#billInfoTableShow select").each(function(e){
		    var inputId = $(this).attr("id");
		    var idArray = inputId.split('_');
		    if($(this).val()!=''){
			    obj2[idArray[1]] = $(this).val();
		    }
		});	
		update_bill(obj2);
	}
	clearBillInput();
}

//增加电费提交
function save_bill(obj){
	$.ajax({
		type:"POST",
		url:"bill/add",
		data:obj,
		dataType :'json',
		timeout:"20000",
		success:function(data,textStatus){
			var msg = data.msg;
			var code = data.code;
			if(code == 0 && 'succ' == msg){
				alert("保存成功");
				$("#managerBill_div").modal("hide");
				$("#stationNo").val(obj['stationNo']);
				$("#table_bill").dataTable().fnDraw();
				clearBillInput();
			}				
		},
		error : function(XMLResponse) {
			alert("提交超时请检查网络环境");
			$("#managerBill_div").modal("hide");
			$("#table_bill").dataTable().fnDraw();
		}
	});
}

//更新基站提交
function update_bill(obj){
	$.post("bill/updateBill",obj, 
    	function(result){
    		if(result == -1){
				alert("系统内部错误,请与管理员联系！");
				$("#managerBill_div").modal("hide");
				$("#table_bill").dataTable().fnDraw();
			}else if(result == 0){
				alert("修改电费条目成功！");
				$("#managerBill_div").modal("hide");
				$("#table_bill").dataTable().fnDraw();
			}
		}
    );
}

//处理基站新增
//简单校验用户输入
function submit_validation(){
	var obj = new Object();
	$("#stationInfoTable input[type='text']").each(function(e){
	    var stationId = $(this).attr("id");
	    var idArray = stationId.split('_');
	    obj[idArray[1]] = $(this).val();
	 });
	var id = $("#station_id_edit").val();
	$("#stationInfoTable select").each(function(e){
	    var stationId = $(this).attr("id");
	    var idArray = stationId.split('_');
	    obj[idArray[1]] = $(this).val();
	 });
	if(id == ''){
		save_station(obj)
	}else{
		update_station(obj)
	}
	clearStationInput();
}

//增加基站提交
function save_station(obj){
	$.ajax({
		type:"POST",
		url:"station/add",
		data:obj,
		dataType :'json',
		timeout:"20000",
		success:function(data,textStatus){
			var msg = data.msg;
			var code = data.code;
			if(code == 0 && 'succ' == msg){
				alert("保存成功");
				$("#managerStation_div").modal("hide");
				$("#table_station").dataTable().fnDraw();
			}				
		},
		error : function(XMLResponse) {
			alert("提交超时请检查网络环境");
			$("#managerStation_div").modal("hide");
			$("#table_station").dataTable().fnDraw();
		}
	});
}

//删除按钮初始化
function deleteBillInit(item) {
	$("#bill_id_delete").val("");
    var tableRow = item.parents('tr')[0];
    var idTh = $(tableRow).children().get(0);
    var stationNameTh = $(tableRow).children().get(4);
    var stationNewNumberTh = $(tableRow).children().get(1);
    var id = $(idTh).text();
    $("#bill_id_delete").val(id);
    var message = "您确定要删除编号:"+id+",的电费条目吗?(本操作不可恢复)"
    $("#deleteBill_p").text(message);
    $("#deleteBill_div").modal("show");
};

//删除电费提交
function delete_bill(){
	$.post("bill/deleteBillById", 
    	{ 
			id:$("#bill_id_delete").val()
    	}, 
    	function(result){
    		if(result == -1){
				alert("系统内部错误,请与管理员联系！");
				$("#deleteBill_div").modal("hide");
				$("#bill_id_delete").val("");
				$("#table_bill").dataTable().fnDraw();
			}else if(result == 0){
				alert("删除电费条目成功！");
				$("#deleteBill_div").modal("hide");
				$("#bill_id_delete").val("");
				$("#table_bill").dataTable().fnDraw();
			}
		}
    );
}


function clearBillInput() {
	$("#billInfoTable input[type='text']").each(function(e) {
		$(this).val("");
	});
	
	$("#billInfoTable select").each(function(e){
		$(this).val("");
	});
	
	$("#billInfoTable textarea").each(function(e){
		$(this).val("");
	});
	
	$("#billInfoTableShow input[type='text']").each(function(e) {
		$(this).val("");
	});
	
	$("#billInfoTableShow select").each(function(e){
		$(this).val("");
	});
	
	$("#billInfoTableShow textarea").each(function(e){
		$(this).val("");
	});
}

function clearStationInput() {
	$("#stationInfoTable input[type='text']").each(function(e) {
		$(this).val("");
	});
}